﻿using B.S.GridManage.Api.Read.Application.Command.DutyGrid;
using B.S.GridManage.Api.Read.Dtos;
using B.S.GridManage.Api.Read.Extension;
using B.S.GridManage.Domain.Entities;
using B.S.GridManage.ErrorCode;
using B.S.GridManage.Infrastructure.Interface;
using MediatR;

namespace B.S.GridManage.Api.Read.Application.Handler.DutyGrid
{
    public class GetDutyGridHander : IRequestHandler<GetDutyGridCommand, ApiResult<List<DutyDto>>>
    {
        private readonly IBaseRepository<DutyGridModel> dutyRepo;
        private readonly IBaseRepository<AreaModel> areaRepo;

        public GetDutyGridHander(IBaseRepository<DutyGridModel> dutyRepo, IBaseRepository<AreaModel> areaRepo)
        {
            this.dutyRepo = dutyRepo;
            this.areaRepo = areaRepo;
        }
        public async Task<ApiResult<List<DutyDto>>> Handle(GetDutyGridCommand request, CancellationToken cancellationToken)
        {
            ApiResult<List<DutyDto>> res = new ApiResult<List<DutyDto>>();

            //表达式
            var dutys = dutyRepo.GetAll().Where(x=>x.IsDeleted==false);
            var areas = areaRepo.GetAll().Where(x => x.IsDeleted == false);

            //条件判断
            if (request.AreaName.IsNotNull()) {
                areas = areas.Where(x=>x.AreaName.Contains(request.AreaName));
            }

            if (request.DutyGridName.IsNotNull()) {
                dutys = dutys.Where(x => x.DutyGridName.Contains(request.DutyGridName));
            }

            //左外联
            var linq = from d in dutys
                       join a in areas on d.AreaId equals a.Id into da
                       from a in da.DefaultIfEmpty()
                       select new DutyDto() { 
                          Id = d.Id,
                           AreaId=a.Id,
                            AreaName=a.AreaName,
                             DutyGridCode=d.DutyGridCode,
                              DutyGridName = d.DutyGridName,
                              DutyGridType = d.DutyGridType,
                               UnitGrids=d.UnitGrids
                       };

            res.Data = linq.ToList();
            res.Msg = "查询责任网格列表成功!";
            res.Code = ApiEnum.Success;

            return res;


        }
    }
}
